﻿using System;
using System.Collections.Generic;
using System.Timers;
using CiStatus.CiStatusAddIn.ViewModels;
using EnvDTE;


namespace CiStatus.CiStatusAddIn.Logic
{
    public class RefreshPump : IRefreshPump, IDisposable
    {
        private readonly IEnumerable<IProject> _projectCollection;
        private readonly Timer _timer;
        private ICallBack _callBack;

        public RefreshPump(double intervalInSeconds, IEnumerable<IProject> projectCollection)
        {
            _projectCollection = projectCollection;
            _timer = new Timer(intervalInSeconds*1000);
            _timer.Elapsed += OnTimerElapsed;
        }

        public bool IsStarted
        {
            get { return _timer.Enabled; }
        }

        public void Start(ICallBack callBack)
        {
            _callBack = callBack;
            _timer.Start();
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            
            foreach (var status in _projectCollection)
            {
                status.Refresh(_callBack);
            }
        }

        public void Stop()
        {
            _timer.Stop();
        }

        public IEnumerable<IProject> ProjectCollection
        {
            get { return _projectCollection; }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the 
        // runtime from inside the finalizer and you should not reference 
        // other objects. Only unmanaged resources can be disposed.
        private void Dispose(bool disposing)
        {
            if (!disposing) return;

            _timer.Stop();
            _timer.Close();
            _timer.Dispose();
        }
    }
}
